<template>
  <div>
    <SearchBar :keyword="condition" :placeholder="placeholder"  :viewoptionArr="viewoptionArr" @handleClickViewOption="handleClickViewOption"
      @hanldeClickFilter="hanldeClickFilter" @handleClickSearch="handleClickSearch"
      @handleInputSearch="handleInputSearch" :isShowListViewIcon="false"></SearchBar>

    <van-popup v-model:show="isShowFilter" position="right" :style="{ height: '100%', width: '90%' }">


      <div class="L-filter-container">

        <!-- 顶部 -->
        <van-row type="flex" align="center" class="L-filter-top-row">
          <van-col :span="3">
            <i class="iconfont icon-fanhui2" style="font-size:22px" @click="isShowFilter = false"></i>
          </van-col>
          <van-col :span="18" class="L-text">
            筛选
          </van-col>
          <van-col :span="3">
            &nbsp;
          </van-col>
        </van-row>

        <!-- 字段 -->
        <div v-for="(item, index) in viewConditions" :key="index" class="L-fliter-field-box">
          <div class="L-text L-bold-text L-margin-10">{{ item.viewcondition_title }}</div>
          <div>
            <FilterInput :uitype="item.viewcondition_uitype" :formItem="item" @handleUpdate="handleUpdate" />
          </div>
        </div>




        <!-- 底部按钮 -->
        <van-row type="flex" align="center" class="L-filter-bottom-row">
          <van-col :span="12">
            <van-button color="#CDD0D6" style="width:80%" @click="handleClear">清空</van-button>
          </van-col>
          <van-col :span="12">
            <van-button color="#1683f7" style="width:80%" @click="handleSearch">查询</van-button>
          </van-col>
        </van-row>
      </div>


    </van-popup>

    <van-popup v-model:show="isShowViewOptions" position="top" :style="{ height: 'auto', width: '100%' }">
      <van-row class="L-viewoption-row" :class="viewoption === item[0] ? 'on' : ''" @click="viewoption = item[0]"
        type="flex" align="center" justify="space-between" v-for="(item, index) in viewoptionArr" :key="index">
        <van-col>{{ item[1] }}</van-col>
        <van-col> <van-icon name="success" v-if="viewoption === item[0]" /></van-col>
      </van-row>
    </van-popup>
    <van-checkbox-group v-model="selectArr">
      <van-list v-model:loading="isLoading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <div class="L-box" v-for="(item, index) in list" :key="index">
          <van-row type="flex">
            <van-col :span="24">
              <div class="L-text L-bold" v-html="item.title"></div>
              <div class="L-secondary-text-color L-small-text" v-html="item.label"></div>
            </van-col>
            <van-col :span="24">
              <div v-if="item.value" >
                <span class="L-secondary-text-color L-small-text" v-html="item.value"></span>
              </div>
              <div style="text-align: right;display: flex;justify-content: end">
                <van-checkbox :name="item.id"></van-checkbox>
              </div>
            </van-col>
          </van-row>
        </div>
      </van-list>
    </van-checkbox-group>

    <div class="L-bottom-space"></div>
    <van-sticky position="bottom">
      <div class="L-bottom-row">
        <!-- <van-button round type="default" style="width:40%" @click="r">取消</van-button> -->
        <van-button round type="primary" style="width:80%" @click="handleConfirm">确定</van-button>
      </div>
    </van-sticky>

  </div>

</template>

<script setup lang="ts">
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();

import {
  onMounted,
  ref,
  watch,
  onActivated,
  defineExpose,
  computed,
  reactive,
  defineEmits
} from "vue";
defineExpose({ onLoad });
import { apiConfigurable } from "@/request/api/api";
import { closeToast, showLoadingToast } from "vant";
import SearchBar from "@/components/common/SearchBar.vue";
import Filter from "@/components/common/Filter.vue";
import FilterInput from "@/components/base/Filter/FilterInput.vue";

import { useCheck } from "@/hooks/hooks.js";
const { checkCustomized } = useCheck();
import emitter from "@/utils/emitter";

import { useRouterStore } from "@/stores/router";
const routerStore = useRouterStore();

onMounted(() => { });
const selectArr = ref([]);

const offset = ref({ x: -20, y: 440 });

const list = ref([]);
const viewConditions = ref([]);
const startline = ref(1);
const pagecount = ref(10); //每页条数
const firstLoad = ref(true); //是否第一次加载
const isLoading = ref(false); //是否加载中
const finished = ref(false); //列表是否加载完成

const sortType = ref(""); //排序方式
const sortBy = ref(""); //排序字段

const extract = ref("");
const searchedtags = ref([]);

const viewoptionArr = ref([]); //视图选项数组
const viewoption = ref(""); //当前视图

const condition = ref(""); //搜索关键字

const sdObject = ref("")
const emits = defineEmits(["back","handleClickFilterFind"]);

sdObject.value = route.query.refobject || ""


function handleClickSearch(value: string) {
  condition.value = value;
  initCondition();
  onLoad();
}

function handleInputSearch(value: string) {
  condition.value = value;
}

//初始化查询条件
function initCondition() {
  startline.value = 1;
  finished.value = false;
  list.value = [];

  conditiondata.value = [];
  sortBy.value = "";
  sortType.value = "asc";
  searchedtags.value = [];

  viewoption.value = "";
}

//显示视图条件
const isShowViewOptions = ref(false);
function handleClickViewOption(value: boolean) {
  isShowViewOptions.value = value;
}
// watch(viewoption, (val) => {
//   isShowViewOptions.value = false;
//   initCondition();
//   onLoad();
// });

function handleUpdate(item,value:string){
  item.viewcondition_value = value
}
//显示过滤层
const isShowFilter = ref(false);
const conditiondata = ref([]);
function hanldeClickFilter(value: boolean) {
  isShowFilter.value = value;
}

function handleClear(){
  viewConditions.value = viewConditions.value.map(item=>{
    item.viewcondition_value = ""
    return item
  })
  emitter.emit('clearFilterInputData')

}


function handleClickFilterFind() {
  initCondition();
  // conditiondata.value = filterObj.fieldArr;
  // sortBy.value = filterObj.sortBy;
  // sortType.value = filterObj.sortType;
  // searchedtags.value = filterObj.selectedTags;
  isShowFilter.value = false;
  onLoad();
}
function handleSearch(){
  handleClickFilterFind()
}
interface tags {
  [id: string]: boolean;
}
interface data {
  [key: string]: any;
}

const props = defineProps({

  loadapi: {
    type: String,
    default: "",
  },
});

const placeholder = ref("")

const sdlist = ref([]);

function onLoad() {
  const { idobject, sdtype, viewid, relopeid, refobject } = route.query;
  const tags: tags = {};

  searchedtags.value.forEach((item) => {
    tags[item] = true;
  });

  let data: data = {
    startline: startline.value,
    pagecount: pagecount.value,
    condition: condition.value,
    orderby: sortBy.value,
    ascdesc: sortType.value,
    viewoption: viewoption.value,
    extract: extract.value,
    tags: JSON.stringify(tags),
    sdtype,
    viewid,
    relopeid,
    refobject,

  };

  for (let i = 0; i < viewConditions.value.length; i++) {
    data[i + "_viewcondition_field"] = viewConditions.value[i].viewcondition_field;
    data[i + "_viewcondition_relfield"] = viewConditions.value[i].viewcondition_relfield;
    data[i + "_viewcondition_value"] = viewConditions.value[i].viewcondition_value;
    data[i + "_viewcondition_comparison"] = viewConditions.value[i].viewcondition_comparison;
    data[i + "_viewcondition_object"] = viewConditions.value[i].viewcondition_object;
    data[i + "_viewcondition_uitype"] = viewConditions.value[i].viewcondition_uitype;
  }

  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });

  isLoading.value = true;

  const loadapi = `${idobject as string}.sdlist.do`;

  apiConfigurable(loadapi, data).then((res) => {
    if (res.data?.jsondata?.fieldValue.length < pagecount.value) {
      finished.value = true;
    }
    list.value = [...list.value, ...res.data?.jsondata?.fieldValue];
    viewConditions.value = res.data?.jsondata?.viewConditions

    sdlist.value = res.data.sdlist || [];

    if(res.data?.jsondata.viewcondition?.length>0){
      
      placeholder.value = res.data?.jsondata.viewcondition.reduce((pre,item,index)=>{
        return `${pre}${index===0 ? '' : '/'}${item.viewcondition_title}`
      },"请输入")
    }

    startline.value = list.value.length + 1;

    closeToast();
    isLoading.value = false;
  });
}

interface sdItemIF {
  refob: string;
  refobs: string;
  sdidview: string;
  sdrelopeid: string;
  sdsubviewid: string;
  sdtitle: string;
  sdtype: string;
  name?: string;
}

const isShowSdAction = ref(false);
const sdActions = computed(() => {
  return sdlist.value.map((item: sdItemIF) => {
    return { name: item.sdtitle, ...item };
  });
});

function handleConfirm() {
  if (selectArr.value.length == 0) {
    return;
  }
  const headid = selectArr.value.join(";");
  const {
    idobject,
    refobject,
    relopeid,
    sdtype,
    viewid,
    subviewid,
    subrefobject,
  } = route.query;
  const path = subviewid ? "sdsub" : "sdnew";//判断是否有子表视图
  router.replace({
    path,
    query: {
      idobject,
      refobject,
      relopeid,
      sdtype,
      subviewid,
      viewid,
      subrefobject,
      headid
    },
  });
}

onActivated(() => {
  if (routerStore.mode === "reload") {
    initCondition();
    onLoad();
    routerStore.mode = "";
  }
});
</script>

<style scoped>
.L-viewoption-row {
  padding: 10px;
}

.L-viewoption-row:active {
  background: #f9f9f9;
}

.on {
  color: #1683f7;
}
</style>